package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class StorageTCCActionImpl implements StorageTCCAction{
    @Autowired
    private StorageMapper storageMapper;

    @Override
    @Transactional
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
        Storage storage=storageMapper.selectById(productId);
        if (storage.getResidue()<count){
            throw  new RuntimeException("库存不足");
        }
        storageMapper.decrease(productId, count);
        //第一阶段完成时保存标记
        ResultHolder.setResult(StorageTCCAction.class, ctx.getXid(),"p" );
        return true;
    }

    @Override
    @Transactional
    public boolean commit(BusinessActionContext ctx) {
        //检查标记是否存在，如果不存在说明之前已将回滚过，不在重复执行回滚
        if (ResultHolder.getResult(StorageTCCAction.class, ctx.getXid())==null){
            return true;
        }
        Long productId=Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count=Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToResidue(productId, count);
        //第二阶段提交完成时，删除标记
        ResultHolder.removeResult(StorageTCCAction.class, ctx.getXid());
        return true;
    }

    @Override
    @Transactional
    public boolean rollback(BusinessActionContext ctx) {
        Long productId=Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count=Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToResidue(productId, count);
        return true;
    }
}
